# -*- coding: utf-8 -*-

import os
import pickle
import glob
import numpy as np
import pandas as pd
import pmdarima as pm
import threading

# 删除历史酒店入住率预测模型文件
def deleteModelFile(filedir, modlelPath):
    file_extension = '*.pkl'
    files_to_delete = glob.glob(filedir + os.sep + file_extension)
    if modlelPath in files_to_delete:
        files_to_delete.remove(modlelPath)

    for file in files_to_delete:
        try:
            os.remove(file)
            pass
        except OSError as e:
            pass

# 酒店入住率预测
def occupancyPrediction(id, currentDateStr, hotelDataDir):
    # global currentDateStr
    # currentDate = datetime.now()
    currentDate = pd.to_datetime(currentDateStr)
    filedir = hotelDataDir + os.sep + str(id)
    # filedir = 'app01' + os.sep + 'static' + os.sep + 'hoteldata' + os.sep + str(id)
    modlelPath = filedir + os.sep + currentDate.strftime('%Y-%m-%d') + '-model.pkl'

    if os.path.exists(modlelPath):
        # 加载模型
        with open(modlelPath, 'rb') as f:
            model = pickle.load(f)
    else:
        deleteModelFile(filedir, modlelPath)
        filePath = filedir + os.sep + 'occupancy.csv'
        df = pd.read_csv(filePath, encoding='utf-8', index_col='time')

        df.index = pd.to_datetime(df.index)  # 将字符串索引转换成时间索引
        df.index = df.index.tz_localize('Asia/Shanghai')

        df = df.loc[:currentDate][:-1]
        ts = df['occupancy']
        model = pm.auto_arima(df, seasonal=True, m=7)
        # 保存模型
        with open(modlelPath, 'wb') as f:
            pickle.dump(model, f)

    forecasts = model.predict(7)
    index_strings = forecasts.index.strftime('%Y-%m-%d')
    return pd.Series(forecasts.values, index=index_strings).to_dict()



print('执行occupancyPrediction')
'''酒店入住率预测'''
hotel_id = 8 # 想要预测的酒店id
currentDateStr = '2023-11-10 23:59:59+08:00'  # 时间字符串，包含时区信息
# hotelDataDir = 'app01' + os.sep + 'static' + os.sep + 'hoteldata' # hoteldata路径
hotelDataDir = './hoteldata'  # hoteldata路径
# 酒店入住率预测
occupancys = occupancyPrediction(hotel_id, currentDateStr, hotelDataDir)
# 以下输出：{'2023-11-08': 0.5399465512164765, '2023-11-09': 0.5526764391387465, '2023-11-10': 0.5476655986689024, '2023-11-11': 0.6381873326981834, '2023-11-12': 0.6445863160074392, '2023-11-13': 0.5562422879476675, '2023-11-14': 0.575672942061773}
# print(occupancys)
print('occupancys-begin=>' + " " + str(occupancys) + " " + 'occupancys-end')

